/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;

        ListNode* ans = new ListNode();
        ListNode* headAns = ans;

        bool carry = false;
        while(cur1 && cur2)
        {
            int a = cur1->val, b = cur2->val;
            int tmp = carry ? a + b + 1 : a + b;
            ans->next = new ListNode(tmp % 10);
            carry = tmp / 10;
            cur1 = cur1->next;
            cur2 = cur2->next;
            ans = ans->next;
        }
        while(cur1)
        {
            int a = carry ? cur1->val + 1 : cur1->val;
            ans->next = new ListNode(a % 10);
            carry = a / 10;
            cur1 = cur1->next;
            ans = ans->next;
        }
        while(cur2)
        {
            int a = carry ? cur2->val + 1 : cur2->val;
            ans->next = new ListNode(a % 10);
            carry = a / 10;
            cur2 = cur2->next;
            ans = ans->next;
        }
        if(carry) ans->next = new ListNode(1);
        ListNode* next = headAns->next;
        headAns->next = nullptr;
        
        return next;
    }
};
